﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace LibNiconico.NiconicoApi.Lives.Broadcast
{
    /// <summary>
    /// 放送可能な情報取得レスポンス
    /// </summary>
    public class NicoLiveBroadcastableInfoGetResponse
    {

        private NicoLiveBroadcastableInfoGetResponse()
        {
            this.broadcastableCommunityInfos = new List<NicoLiveBroadcastableCommunityInfo>();
        }

        private List<NicoLiveBroadcastableCommunityInfo> broadcastableCommunityInfos;

        /// <summary>
        /// 放送可能なコミュニティ情報
        /// </summary>
        public IEnumerable<NicoLiveBroadcastableCommunityInfo> BroadcastableCommunityInfos
        {
            get
            {
                return broadcastableCommunityInfos;
            }
        }

        /// <summary>
        /// 取得に成功したか判定
        /// </summary>
        public bool Succeed
        {

            get
            {
                return BroadcastableCommunityInfos.Count() > 0;
            }

        }

        internal static NicoLiveBroadcastableInfoGetResponse Parse(XDocument document)
        {
            var response = new NicoLiveBroadcastableInfoGetResponse();
            var communityRegex = new Regex(@".*co[0-9]+.*");
            var comlvRegex = new Regex(@".*comlv[0-9]+.*");


            response.broadcastableCommunityInfos.AddRange(from communityInfo in document.Descendants("option")
                                                          where communityInfo.Attribute("value") != null && communityRegex.IsMatch((string)communityInfo.Attribute("value")) && 
                                                          communityInfo.Attribute("class") != null && comlvRegex.IsMatch((string)communityInfo.Attribute("class")) && 
                                                          communityInfo.Value != null
                                                          select NicoLiveBroadcastableCommunityInfo.Parse((string)communityInfo.Attribute("value"),communityInfo.Value,(string)communityInfo.Attribute("class")));

            return response;
        }
    }
}
